<?php
/**
 * @desc 接受用户中心同步的数据
 * @author sundongdong
 * @date 2016-07-11
 */
class Interface_UserController extends Controller_Base {
	public function init() {
		parent::init();
		$this->model = new Application_Model_User();
		$this->logs = new Log();
		$this->system_name   = 'System';
	}
	public function indexAction() {
		$key  = $this->getRequest()->getParam('key');
		$data = $this->getRequest()->getParam('data');
		$local_key = $this->md5Encrypt($data);
		// 验证key
		if ($key != $local_key) {
			$this->logs->record("| 密钥匹配错误 | 接收密钥 : ".$key." | 本地密钥 : ".$local_key." |  接收数据 : ".urldecode($data));
			die(json_encode(array('opr'=>-1, 'content'=>'key error')));
		}
		$user = json_decode($data, true);
		//如果目标用户名为空,结束
		if (empty($user['username'])){
			$this->logs->record("|用户名为空错误 |  接收数据 : ".urldecode($data));
			die(json_encode(array("opr"=>-1,"content"=>"Username Error!")));
		}
		
		$returnArr = array();
		// 更新类型
		$type = intval($user['type']);
		
		$new_data = array();
		$new_data['user_name'] = $user['username'];
		$new_data['department_id'] = $user['userinfo']['department_id'];
		$new_data['real_name'] = $user['name'];
		$new_data['is_group_leader'] = $user['userinfo']['is_group_leader'];
		$new_data['is_enable'] = $user['userinfo']['is_lock'] ? 0 : 1;
		// 检查用户是否已经存在
		$user_id = $this->model->exist($user['username']);
		switch ($type) {
			case 1: // 新增
				if ($user_id) {
					$returnArr = $this->model->update($new_data, $user_id);
				} else {
					$returnArr = $this->model->add($new_data);
				}
				break;
			case 2: // 修改
				if ($user_id) {
					$returnArr = $this->model->update($new_data, $user_id);
				} else {
					$returnArr = $this->model->add($new_data);
				}
				break;
			case 3: // 删除
				if ($user_id) {
					$returnArr = $this->model->delete($user['account']);
				} else {
					$returnArr = array('opr'=>'-1', 'content'=>'非法删除，用户不存在');
				}
				break;
		}
		echo json_encode($returnArr);
	}
	/**	
	 * 同步用户
	 */
	public function syncAction() {
		$ssoHost = Helper_Config::get('base', 'sso', 'host');
		$uurl = $ssoHost . "/login/safelog/listusers/";
		$data = array('1');
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uurl );
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    //用于返回的原始输出
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data );  //传输内容
		$response = curl_exec( $ch );
		curl_close( $ch );
		$users = @json_decode($response, true);
		$user_model = new Application_Model_User();
		$bench = array();
		foreach ($users as $user) {
			// 不存在则添加
			if (!$user_model->exist($user['account'])) {
				$data = array();
				$data['user_name'] = $user['username'];
				$data['department_id'] = $user['department_id'];
				$data['real_name'] = $user['name'];
				$data['is_group_leader'] = $user['is_group_leader'];
				$data['is_enable'] = $user['is_lock'] ? 0 : 1;
	
				$bench[] = $data;
			}
		}
		try {
			$user_model->addUsers($bench);
		} catch (Exception $e) {
			exit($e->getMessage());
		}
		echo "success";
	}
	/**
	 * 系部同步
	 */
	public function deptAction() {
		$key  = $this->getRequest()->getParam('key');
		$json = $this->getRequest()->getParam('data');
		$local_key = $this->md5Encrypt($json);
		// 验证key
		if ($key != $local_key) {
			$this->logs->record("| 密钥匹配错误 | 接收密钥 : ".$key." | 本地密钥 : ".$local_key." |  接收数据 : ".urldecode($json));
			die(json_encode(array('opr'=>-1, 'content'=>'key error')));
		}
		$data = json_decode(iconv('gbk','utf-8',urldecode($json)),true);
		$deptdata = $data['data'];
		$resArr = array(); //返回同步结果;
		$dept_api = new Interface_Model_Department();
		//获取用户中的系部id，判断系部是否存在，如果存在返回系部信息，否则返回false
		$isExist = $dept_api->existDept($deptdata['id']);
		$wdb = Model_Db::getInstance('write_db');
		$wdb->beginTransaction();
		try {
			if ($isExist) {
				$update = [
					'department_name' => $deptdata['department_name'],
					'parent_id' => $deptdata['parent_id'],
					'status' => $deptdata['enable'],
				];
				$dept_api->updateDept($update, $isExist);	
			} else {
				$insert = [
					'department_id' => $deptdata['id'],
					'department_name' => $deptdata['department_name'],
					'parent_id' => $deptdata['parent_id'],
					'status' => $deptdata['enable'],
				];
				$dept_api->insertDept($insert);
			}
			$wdb->commit();
			exit(json_encode(array("opr"=>1,"content"=>"success")));
		}catch (Exception $e) {
			exit(json_encode(array("opr"=>-1,"content"=>$e->getMessage())));
		}
	}
}